package com.zhuxulin.tab.threads;

import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.zhuxulin.midi.event.MidiEvent;
import com.zhuxulin.midi.util.MidiUtil;
import com.zhuxulin.midi.util.PianoUtils;
import com.zhuxulin.midi.util.PianoUtils2;
import com.zhuxulin.tab.App;
import com.zhuxulin.tab.bluetooth.ISendMsg;

public class PlayPianoUerTimer {
	private File mid = null;
	private Timer timer = null;
	private boolean isStart = false;
	private PianoUtils2 piano = null;
	private App app = null;
	private ISendMsg sendMsg = null;

	public PlayPianoUerTimer(App app) {
		this.app = app;
	}

	// public PlayPianoUerTimer(File mid) {
	// this.mid=mid;
	// piano=new Piano(mid);
	// }
	// public PlayPianoUerTimer(String mid) {
	// this.mid=new File(mid);
	// piano=new Piano(mid);
	// }
	public void setFile(File mid) {
		// this.mid=mid;
		piano = new PianoUtils2(mid);
	}

	public void setFile(String mid) {
		// this.mid=new File(mid);
		piano = new PianoUtils2(mid);
	}

	public void setSendMsg(ISendMsg sendMsg) {
		this.sendMsg = sendMsg;
	}

	public void cancle() {
		if (timer != null) {
			timer.cancel();
		}
	}

	public boolean isStart() {
		return this.isStart;
	}

	public void start() {
		isStart = true;
		timer = new Timer();
		timer.schedule(new Task(app.getSendMsg(), piano, timer, 0), 0);
	}
}

class Task extends TimerTask {
	private static float BPM = 120.0f;
	private static int MPQN = (int) (60000000 / BPM);
	private long now = 0;
	private long next = 0;
	private Timer timer = null;
	private PianoUtils2 piano = null;
	private ISendMsg sendMsg = null;

	public Task(ISendMsg sendMsg, PianoUtils2 piano, Timer timer, long now) {
		this.sendMsg = sendMsg;
		this.piano = piano;
		this.timer = timer;
		this.now = now;
		this.next = piano.getNextTick(now);
	}

	@Override
	public void run() {
		// System.out.println(piano.getEventsWithTick(now));
		sendList(piano.getEventsWithTick(now));
		System.out.println(next - now);
		if (next == -1) {
			timer.cancel();
			System.out.println("Cancle!");
			return;
		}
		timer.schedule(new Task(sendMsg, piano, timer, next),
				MidiUtil.ticksToMs(next - now, MPQN, piano.getResolution()));
		System.out.println(piano.getLengthInTicks());
	}

	private void sendList(List<MidiEvent> events) {
		for (MidiEvent e : events) {
			sendMsg.sendMessage(e.getCmd());
			System.out.println(e);
		}
	}
}